package br.com.academia.DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import br.com.academia.beans.Filial;

public class FilialDAO {

	private Connection connection;

	public FilialDAO(Connection connection) {
		this.connection = connection;
	}
	
	public List<String[]> consultaFiliais(List<String> dadosConsulta)  {
		List<String[]> retorno = new ArrayList<String[]>();
		String query = "Select idFilial, Empresa_idEmpresa, Empresas.nomeFantasia," +
				"endereco, numero, cep, bairro, descricao from Filiais " +
				"Left Join Empresas on Filiais.Empresa_idEmpresa = Empresas.idEmpresa";
		 try {
			 PreparedStatement stm = connection.prepareStatement(query);
			 ResultSet rs = stm.executeQuery();
			 while(rs.next()) {
				 String[] row = new String[dadosConsulta.size()];
				 for(int i = 0; i < row.length; i++) {
					 row[i] = rs.getString(dadosConsulta.get(i));
				 }
				 retorno.add(row);
			 }
		 } catch(SQLException e) {
			 e.printStackTrace();
		 }
		return retorno;
	}
	
	public Filial consultaFilialId(int idFilial) {
		Filial filial = new Filial();
		String query = "Select * from Filiais where idFilial = ?";
		try {
			PreparedStatement stm = connection.prepareStatement(query);
			stm.setInt(1, idFilial);
			ResultSet rs = stm.executeQuery();
			
			if(rs.next()) {
				filial.setIdFilial(rs.getInt("idFilial"));
				filial.setEmpresa_idEmpresa(rs.getInt("Empresa_idEmpresa"));
				filial.setEndereco(rs.getString("endereco"));
				filial.setNumero(rs.getInt("numero"));
				filial.setCep(rs.getInt("cep"));
				filial.setBairro(rs.getString("bairro"));
				filial.setDescricao(rs.getString("descricao"));
				
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
		
		return filial;
	}
	
	public List<Filial> buscaFilialSelecao() {
		List<Filial> listaFilial = new ArrayList<Filial>();
		String query = "Select idFilial, endereco from Filiais";

		try {
			PreparedStatement stm = connection.prepareStatement(query);
			ResultSet rs = stm.executeQuery();

			while (rs.next()) {
				Filial filial = new Filial();
				filial.setIdFilial(rs.getInt("idFilial"));
				filial.setEndereco(rs.getString("endereco"));
				listaFilial.add(filial);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return listaFilial;
	}
	
}
